<template>
  <div>
    <div class="loading-box" v-if="loading">
      <van-loading type="spinner" color="#1989fa" />
    </div>
    <div class="pageData" v-else>
      <Hander :isshow="false"></Hander>

      <!-- 页面最外层容器，设置背景色、最小高度占满屏幕等样式 -->
      <div class="page-container">
        <!-- <div class="header">
      <h1>智慧生活-共享吹风</h1>
      <div class="school-info">
        <img
          src="../assets/logo.png"
          alt="西南石油大学校徽"
          class="school-logo"
        />
        <img
          src="../assets/chuifengji.png"
          alt="西南石油大学校徽"
          class="school-logo-right"
        />
      </div>
    </div> -->

        <div class="info-content">
          <!-- 用户信息卡片 -->
          <div class="user-card">
            <img
              src="../assets/avatar.png"
              alt="用户头像"
              class="user-avatar"
            />
            <div class="user-info">
              <span class="user-name">{{ userInfo.name }}</span>
              <span class="user-phone">学号：{{ userInfo.account }}</span>
              <span class="user-phone">电话：{{ userInfo.phone }}</span>
            </div>
            <span class="user-role">
              {{
                userInfo.userType == "student"
                  ? "学生"
                  : userInfo.userType == "staff"
                  ? "教职工"
                  : userInfo.userType == "worker"
                  ? "巡检工作人员"
                  : userInfo.userType == "guest"
                  ? "游客"
                  : "未知"
              }}</span
            >
          </div>

          <!-- 使用说明标题 -->
          <div class="instruction-container">
            <div class="usage-title">
              <img class="icon" src="@/assets/zc.svg" alt="" />
              <span class="title-text">使用说明</span>
              <img class="icon" src="@/assets/yc.svg" alt="" />
            </div>
          </div>

          <!-- 使用说明内容区域 -->
          <div class="usage-instruction">
            <div v-html="valueHtml"></div>
          </div>
        </div>

        <!-- 功能按钮区域，包含“使用记录”“设备状态”按钮 -->
        <div class="button-tag function-buttons">
          <!-- 使用记录按钮，图片与文字水平排列 -->
          <button
            class="function-btn"
            @click="handleButtonClick('usageRecord')"
          >
            <img src="../assets/syjl.png" alt="使用记录图标" class="btn-icon" />
            使用记录
          </button>

          <!-- 分隔线 -->
          <div class="divider"></div>

          <!-- 设备状态按钮 -->
          <button
            class="function-btn"
            @click="handleButtonClick('deviceStatus')"
          >
            <img src="../assets/sbzt.png" alt="使用记录图标" class="btn-icon" />
            设备状态
          </button>
        </div>

        <!-- 扫码使用按钮 -->
        <button class="scan-button function-btn" @click="handleScanClick">
          <img src="../assets/ewm.png" alt="使用记录图标" class="btn-icon" />
          扫码使用
        </button>

        <Qrcode ref="qrcode" @goBack="goBack" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";

import Hander from "@/components/hander.vue";
import UserHand from "@/components/userHand.vue";
import Qrcode from "@/components/qrcode.vue";

import { wechatConfig, scanQRCode } from "../wechatSdk.js";

import { compususerinfo, announcementsfindAll } from "@/api/index.js";

import { useCounterStore } from "@/stores/counter";
const counterStore = useCounterStore();

const route = useRoute();
const router = useRouter();

// 按钮点击事件处理函数
const handleButtonClick = (type) => {
  if (type === "usageRecord") {
    console.log("点击了使用记录按钮");
    router.push("/usageRecord");
  } else if (type === "deviceStatus") {
    console.log("点击了设备状态按钮");
    router.push("/reportLossList");
  }
};

// 扫码使用按钮点击事件处理函数
const qrcode = ref();
const handleScanClick = async () => {
  // console.log("点击了扫码使用按钮");
  // qrcode.value.getCameras();

  try {
    const result = await scanQRCode(this, {
      needResult: true,
      scanType: ["qrCode"], // 仅扫描二维码
      onSuccess: (res) => {
        console.log("扫码成功: " + res.resultStr);
      },
      onError: (err) => {
        console.log("扫码失败",err);
        showToast("验收失败请稍后重试");
      },
    });
    console.log("扫码结果:", result.resultStr);
    // 这里可以处理扫码结果（如跳转页面）
    const id = result.resultStr.split("?id=")[1]; // 直接分割 "?id=" 并取第二部分
    router.push({
      path: "/payment",
      query: { id: id }, // 传递参数 id=10
    });
  } catch (error) {
    console.log("调用扫一扫失败:", error);
  }
};

//扫码结果
const goBack = (data) => {
  //DH202507190001
  console.log("扫码结果:", data);
  const id = data.split("?id=")[1]; // 直接分割 "?id=" 并取第二部分

  router.push({
    path: "/payment",
    query: { id: id }, // 传递参数 id=10
  });
};

// 获取注意事项
let zyList = ref({});
let valueHtml = ref("");
const getannouncementsfindAll = async () => {
  try {
    let res = await announcementsfindAll({
      page: 1,
      size: 1,
    });
    //如果获取到数据
    zyList.value = res.data;

    valueHtml.value = zyList.value.content;
  } catch (error) {}
};

//获取userInfo
let loading = ref(false);
let userInfo = ref({});
const getcompususerinfo = async () => {
  try {
    loading.value = true;
    const res = await compususerinfo({
      query: decodeURIComponent(
        getTokenFromUrl() ? getTokenFromUrl() : counterStore.token
      ), //调用方法---获取页面token
    });
    if (res.code == 200) {
      // 调用 Pinia 的 action 保存 token
      userInfo.value = res.data;
      counterStore.CLEAR_ACTION(res.data);
      loading.value = false;
    } else {
      loading.value = false;
      showToastAuth();
    }
  } catch (error) {
    loading.value = false;
    showToast(error);
    showToastAuth();
  }
};

const showToastAuth = () => {
  showConfirmDialog({
    title: "提示",
    "show-cancel-button": false,
    message:
      "未获取到用户信息，请进入西南石油大学后勤服务大厅，点击吹风/插座应用进行授权使用。",
  })
    .then(() => {
      // 注册
      window.location.href = "https://hqfw.swpu.edu.cn/appLogin";
    })
    .catch(() => {
      // on cancel
    });
};

// 从 URL 参数中获取 token
const getTokenFromUrl = () => {
  //获取所有的完整地址
  const allPath = window.location.href;
  //判断是否有问号
  if (allPath.indexOf("?") === -1) return null;
  //截取问号后面的token值
  const token = allPath.split("?")[1];
  //判断是否有token参数
  if (!token || token.indexOf("query=") === -1) return null;
  //获取token值
  const tokenValue = token.split("=")[1];
  // 调用 Pinia 的 action 保存 token
  counterStore.TOKEN_ACTION(tokenValue);

  return tokenValue;
};

onMounted(() => {
  getcompususerinfo();
  getannouncementsfindAll();
  wechatConfig(); //配置
});
</script>

<style scoped>
.loading-box {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pageData {
  min-height: 100vh;
  background-color: rgba(71, 188, 145, 1);
}

.page-container {
  background-color: rgba(71, 188, 145, 1);
  padding: 0 2.13vh; /* 16px / 750px * 100vh ≈ 2.13vh */
  color: #fff;
}

.info-content {
  background-color: #fff;
  border-radius: 2vh; /* 15px / 750px * 100vh ≈ 2vh */
  /* margin-top: 5.6vh;  */
  color: #000;
  height: 57vh;
  position: relative;
  z-index: 1;
}

.user-card {
  display: flex;
  align-items: center;
  border-radius: 1.07vh; /* 8px / 750px * 100vh ≈ 1.07vh */
  padding: 3vh 1.8vh; /* 30px 20px → 4vh 2.67vh */
}

.user-avatar {
  width: 8vh; /* 60px / 750px * 100vh ≈ 8vh */
  height: 8vh;
  border-radius: 50%;
  margin-right: 1.6vh; /* 12px / 750px * 100vh ≈ 1.6vh */
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 2.13vh; /* 16px / 750px * 100vh ≈ 2.13vh */
  font-weight: bold;
  margin-bottom: 0.53vh; /* 4px / 750px * 100vh ≈ 0.53vh */
}

.user-phone {
  font-size: 14px; /* 14px / 750px * 100vh ≈ 1.87vh */
}

.color1 {
  color: #1b1b1b;
}

.user-role {
  margin-left: auto;
  background-color: #fff;
  color: #4caf50;
  padding: 0.53vh 1.07vh; /* 4px 8px → 0.53vh 1.07vh */
  border-radius: 0.53vh; /* 4px / 750px * 100vh ≈ 0.53vh */
  font-size: 1.6vh; /* 12px / 750px * 100vh ≈ 1.6vh */

  font-weight: 400;
  color: #47ba7f;
  box-sizing: border-box;
  padding: 0.4vh 1.2vh; /* 3px → 0.4vh; 9px → 1.2vh */
  background-color: #dffff4;
}

.usage-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 1.33vh; /* 10px / 750px * 100vh ≈ 1.33vh */
}

.icon {
  width: 30%;
  font-size: 1.87vh; /* 14px / 750px * 100vh ≈ 1.87vh */
  margin: 0 1.33vh; /* 0 10px → 0 1.33vh */
}

.title-text {
  font-size: 2.67vh; /* 20px / 750px * 100vh ≈ 2.67vh */
  font-weight: bold;
}

.usage-instruction {
  height: 35vh;
  overflow-y: auto;
  padding: 0.67vh 2.67vh; /* 5px 20px → 0.67vh 2.67vh */
  margin-bottom: 0.13vh; /* 1px / 750px * 100vh ≈ 0.13vh */
}

.usage-instruction h3 {
  font-size: 1.87vh; /* 14px / 750px * 100vh ≈ 1.87vh */
  font-weight: bold;
  margin: 1.07vh 0 0.53vh; /* 8px 0 4px → 1.07vh 0 0.53vh */
}

.usage-instruction p {
  font-size: 1.6vh; /* 12px / 750px * 100vh ≈ 1.6vh */
  line-height: 1.5;
}

.function-buttons {
  display: flex;
  justify-content: space-around;
  margin-bottom: 1.07vh; /* 8px / 750px * 100vh ≈ 1.07vh */
  height: 10.67vh; /* 80px / 750px * 100vh ≈ 10.67vh */
  line-height: 10.67vh;
}

.function-btn {
  background-color: #fff;
  border: none;
  padding: 0 2.13vh; /* 0 16px → 0 2.13vh */
  border-radius: 2.67vh; /* 20px / 750px * 100vh ≈ 2.67vh */
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  font-size: 2.4vh; /* 18px / 750px * 100vh ≈ 2.4vh */
}

.btn-icon {
  width: 3.47vh; /* 26px / 750px * 100vh ≈ 3.47vh */
  height: 4vh; /* 30px / 750px * 100vh ≈ 4vh */
  margin-right: 1.07vh; /* 8px / 750px * 100vh ≈ 1.07vh */
}

.button-tag {
  color: #000;
  margin-top: 1.6vh; /* 12px / 750px * 100vh ≈ 1.6vh */
  background-color: #fff;
  border-radius: 1.6vh; /* 12px / 750px * 100vh ≈ 1.6vh */
}

.divider {
  width: 0.27vh; /* 2px / 750px * 100vh ≈ 0.27vh */
  height: 5.33vh; /* 40px / 750px * 100vh ≈ 5.33vh */
  background: #e3e3e3;
  margin: auto 0;
}

.scan-button {
  color: #000;
  width: 100%;
  background-color: #fff;
  border: none;
  padding: 1.6vh; /* 12px / 750px * 100vh ≈ 1.6vh */
  margin-top: 1.33vh; /* 10px / 750px * 100vh ≈ 1.33vh */
  border-radius: 2.67vh; /* 20px / 750px * 100vh ≈ 2.67vh */
  font-size: 2.4vh; /* 18px / 750px * 100vh ≈ 2.4vh */
  cursor: pointer;
}
</style>
